package net.internet;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class PooledWebLog
{
	private BufferedReader	in;
	private BufferedWriter	out;
	private int				numberOfThreads;
	@SuppressWarnings({ "unchecked", "rawtypes" })
	private List	entries		= Collections.synchronizedList(new LinkedList());
	private boolean			finished	= false;
	@SuppressWarnings("unused")
	private int				test		= 0;
	
	public PooledWebLog(InputStream in, OutputStream out, int numberOfThreads)
	{
		this.in = new BufferedReader(new InputStreamReader(in));
		this.out = new BufferedWriter(new OutputStreamWriter(out));
		this.numberOfThreads = numberOfThreads;
	}
	public boolean isFinished()
	{
		return this.finished;
	}
	public int getNumberOfThreads()
	{
		return numberOfThreads;
	}
	@SuppressWarnings("unchecked")
	public void processLogFile()
	{
		for (int i = 0; i < numberOfThreads; i++)
		{
			Thread t = new LookupThread(entries, this);
			t.start();
		}
		try
		{
			String entry = in.readLine();
			while(entry!=null)
			{
				if(entries.size()>numberOfThreads)
				{
					try
					{
						Thread.sleep(1000/numberOfThreads);
					}
					catch (Exception e)
					{
						continue;
					}
				}
				synchronized (entries)
				{
					entries.add(0,entry);
					entries.notifyAll();
				}
				entry = in.readLine();
				Thread.yield();
			}
		}
		catch (Exception e)
		{
		}
		this.finished = true;
		synchronized (entries)
		{
			entries.notifyAll();
		}
	}
	public void log(String entry) throws IOException
	{
		out.write(entry);
		out.flush();
	}
	public static void main(String[] args)
	{
		try
		{
			PooledWebLog tw = new PooledWebLog(new FileInputStream(args[0]), System.out, 100);
			tw.processLogFile();
		}
		catch (Exception e)
		{
		}
	}
}
